#! -*- coding: utf-8 -*-

from script_utils import query, oid2nid, get_one2list
from script_utils import models

cols = {
    "userplan": [
        'id',
        'user_id',
        'name',
        'city_names',
        'device_id',
        'is_active',
        'app_data',
        'share_id',
        'qiniu_cover',
        'is_share',
        'create_date',
        'last_modified',
        'date_added',
    ],
    'planordermtu': [
        'id',
        'order_id',
        'mtu_id',
        'hotel_id',
        'hotel_order_id',
        'destination_id',
        'is_special',
        'is_active',
        'last_modified',
        'date_added',
    ],
}


def migrate_userplan():
    userplan_id2planordermtu_ids = get_one2list('vacation_planordermtu', 'plan_id', 'id')

    for row in query('vacation_userplan', cols=cols['userplan']):
        userplan = dict(zip(cols['userplan'], row))
        oid = userplan['id']
        userplan['id'] = oid2nid["vacation_userplan"][oid]

        # 'planordermtu'
        userplan['planordermtu'] = [oid2nid["vacation_planordermtu"][planordermtu_id] for planordermtu_id in
                                    userplan_id2planordermtu_ids.get(oid, [])]

        models.UserPlan.objects.create(**userplan)


def migrate_planordermtu():
    for row in query('vacation_planordermtu', cols=cols['planordermtu']):
        obj = dict(zip(cols['planordermtu'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_planordermtu"][oid]

        obj_order_id = oid2nid["vacation_productorder"][obj['order_id']] if obj['order_id'] else None
        obj['order'] = obj_order_id
        del obj['order_id']

        obj_mtu_id = oid2nid["vacation_mtu"][obj['mtu_id']] if obj['mtu_id'] else None
        obj['mtu'] = obj_mtu_id
        del obj['mtu_id']

        obj_destination_id = oid2nid["vacation_destination"][obj['destination_id']] if obj['destination_id'] else None
        obj['destination'] = obj_destination_id
        del obj['destination_id']

        models.PlanOrderMtu.objects.create(**obj)


if __name__ == "__main__":
    print 'migrate userplan start...'
    migrate_userplan()
    print 'migrate userplan end...'

    print 'migrate planordermtu start...'
    migrate_planordermtu()
    print 'migrate vacation_planordermtu end...'
